package org.leumasjaffe.initiativeTracker.entity;


import java.util.ArrayList;
import java.util.Collection;
import java.util.Hashtable;

import org.eclipse.jdt.annotation.NonNullByDefault;
import org.leumasjaffe.initiativeTracker.operator.CharacterLinker;

@NonNullByDefault
public class CharacterList {
	ArrayList<CharacterLinker> characters = new ArrayList<CharacterLinker>();
	Hashtable<Integer, CharacterLinker> lookup = new Hashtable<Integer, CharacterLinker>();

	@SuppressWarnings("null")
	public ArrayList<CharacterLinker> getList() {
		return this.characters;
	}
	
	public void setList(ArrayList<CharacterLinker> list) {
		this.characters = list;
		for (CharacterLinker cl : list)
			this.lookup.put(cl.getCharacter().getId(), cl);
	}
	
	public void add(CharacterLinker cl) {
		this.characters.add(cl);
		this.lookup.put(cl.getCharacter().getId(), cl);
	}
	
	public void clear() {
		this.characters.clear();
		this.lookup.clear();
	}
	
	public void add(int index, CharacterLinker cl) {
		this.characters.add(index, cl);
		this.lookup.put(cl.getCharacter().getId(), cl);
	}
	
	public CharacterLinker remove(int index) {
		CharacterLinker cl = this.characters.remove(index);
		this.lookup.remove(cl.getCharacter().getId());
		return cl;
	}
	
	@SuppressWarnings("null")
	public CharacterLinker get(int index) {
		return this.characters.get(index);
	}

	public int size() {
		return this.characters.size();
	}
	
	public CharacterLinker remove(CharacterLinker cl) {
		this.characters.remove(cl);
		this.lookup.remove(cl.getCharacter().getId());
		return cl;
	}
	
	public void set(int index, CharacterLinker cl) {
		this.characters.set(index, cl);
		this.lookup.put(cl.getCharacter().getId(), cl);
	}

	@SuppressWarnings("null")
	public CharacterLinker lookup(int id) {
		return this.lookup.get(id);
	}
	
	@SuppressWarnings("null")
	public Collection<Integer> keyset() {
		return this.lookup.keySet();
	}
	
	/**
	 * Inserts a given Character into the allPieces array
	 * @param c The character to be inserted
	 */
	public void insert(CharacterLinker c) {
		if (size() == 0) {
			add(c);
		}
		else {
			boolean done = false;
			int charInit = c.getCharacter().getInit();
			for (int i = 0; i<size(); i++) {
				Character get = get(i).getCharacter();
				int getInit = get.getInit();
				if (charInit > getInit ||
						(charInit == getInit && c.getCharacter().getName()
								.compareToIgnoreCase(get.getName()) < 0)) {
					add(i, c);
					done = true;
					break;
				}
			}
			if (!done) {
				add(c);
			}
		}
	}

}
